import platform = require('../common/baseCommon');
import bpCommon = require('../common/bpCommon');
import appServer = require('./appServer');
import appClient = require('../../platform/client/appClient');
import { baseService } from '../common/baseCommon';
import { debug } from 'util';
import { fileLogger } from './appServer';

const moduleName = "platform.server";


/** 
 * 用户登录接口
*/
@platform.addon("用户登录服务", "用户登录服务（可用于远程代理）", moduleName)
export class UserLoginService extends baseService implements bpCommon.IUserLogin, platform.IFeatureSupport {

    /**
     * 特性控制器
     */
    featureController?: platform.baseFeatureController;
    /**
    * 手机登录信息
    */
    Phonelogininfo?: Object = {};
    /**
     * 密码
     */
    password?: string = "";
    /**
     * 登录
     * @param userinfo 用户信息
     */
    login(usertoken: platform.userToken): Promise<platform.ResponseMessage<platform.userToken>> {
        let that = this;
        let huser = this.rqHeader.userToken;
        let rs = new platform.ResponseMessage<platform.userToken>();//返回对象
        let user = usertoken.userinfo;
        let dataService: platform.IDataService = appServer.globalServices["webptDataService"];
        user.lastOptTime = new Date();
        user.userId = "userID";
        user.status = "00";
        //判断用户登录方式，根据不同登录方式sql传值不同
        if (user.loginType == "Mobile") {//手机登录方式
            return dataService.query("cmd_user_role", { "MOBILE": user.mobile })
                .then((table: platform.dataTable) => {
                    table.rows.forEach(element => {
                        that.password = element.rowValues["PASSWORD"];
                        user.name = element.rowValues["USER_NAME"];
                        let r: platform.role = new platform.role();
                        r.id = element.rowValues["ROLE_ID"];
                        r.name = element.rowValues["ROLE_NAME"];
                        user.roles.push(r);
                    });
                    user.userId = table.rows[0].rowValues["USER_ID"];
                    user.name = table.rows[0].rowValues["USER_NAME"];
                    user.mobile = table.rows[0].rowValues["MOBILE"];
                    rs.header.rtnCode = "00";
                    rs.header.rtnMsg.message = "成功";
                    rs.body = usertoken;
                    return rs;

                }).catch(error => {
                    if (error.errno == "ETIMEDOUT") {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "服务器繁忙请稍候再试！";
                        return rs;
                    } else {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "该手机号码没有绑定用户";
                        return rs;
                    }

                });
        } else {//账号登录方式
            return dataService.query("cmd_user_role", { "ID": user.logingAccount })
                .then((table: platform.dataTable) => {
                    table.rows.forEach(element => {
                        that.password = element.rowValues["PASSWORD"];
                        user.name = element.rowValues["USER_NAME"];
                        let r: platform.role = new platform.role();
                        r.id = element.rowValues["ROLE_ID"];
                        r.name = element.rowValues["ROLE_NAME"];
                        user.roles.push(r);
                    });
                    user.userId = table.rows[0].rowValues["USER_ID"];
                    user.name = table.rows[0].rowValues["USER_NAME"];
                    var md5password = appServer.encrypt.calMd5(user.password);
                    if (md5password != that.password) {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "登录失败,用户名或密码出错";
                        return rs;
                    } else {
                        rs.header.rtnCode = "00";
                        rs.header.rtnMsg.message = "成功";
                        rs.body = usertoken;
                        return rs;
                    }
                }).catch(error => {
                    if (error.errno == "ETIMEDOUT") {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "服务器繁忙请稍候再试！";
                        return rs;
                    } else {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "登录失败，用户名或密码出错";
                        return rs;
                    }
                });
        }
    }

    /**
     * 获取手机验证码
     * @param phoneNo 手机号码
    */
    getCode(mobile: string, tpl_id: number, codeLen: number) {
        try {
            let smsplatformservice: bpCommon.ISMSPlatform = appServer.globalServices["getcodeService"];
            smsplatformservice.sendverificationcode(mobile, tpl_id, codeLen).then((value) => {
                //将不同用户手机验证码与获取验证码时间存储到对象里，用于校验与判断超时
                let obj: Object = new Object();
                obj["code"] = value;
                obj["getTime"] = new Date().getTime() / 1000;
                this.Phonelogininfo[mobile] = obj;
                console.log(this.Phonelogininfo);
            });

        } catch (error) {
            console.log(error.message.responseText);
            alert(JSON.parse(error.message).responseText);
        }

    }
    /**
     * 校验验证码
     */
    codelogin(mobile: string, vrcode: string): Promise<platform.ResponseMessage<any>> {
        return Promise.resolve().then(() => {
            let rs = new platform.ResponseMessage<any>();//返回对象
            let nowdate = new Date().getTime() / 1000;//获取当前登录时间
            if (this.Phonelogininfo[mobile] != null) {
                let timedifference = nowdate - this.Phonelogininfo[mobile].getTime;//计算获取验证码时间与登记时间差
                if (timedifference > 180) {//如果时间差大于3分钟则判断验证码超时失效
                    rs.header.rtnCode = "01";
                    rs.header.rtnMsg.message = "验证码已失效，请重新获取";
                    return rs;
                } else {
                    if (vrcode == this.Phonelogininfo[mobile].code) {
                        rs.header.rtnCode = "00";
                        rs.header.rtnMsg.message = "成功";
                        return rs;
                    } else {
                        rs.header.rtnCode = "01";
                        rs.header.rtnMsg.message = "输入验证码不正确！";
                        return rs;
                    }
                }
            } else {
                rs.header.rtnCode = "01";
                rs.header.rtnMsg.message = "该手机号码未获取验证码，请重新获取";
                return rs;
            }

        })
    }
    /**
     * 登出
     * @param user 用户信息
     */
    logout(userRq: platform.userToken): Promise<platform.ResponseMessage<platform.userToken>> {
        let user = this.rqHeader.userToken;
        //获取当前用户对当前方法生效的特性
        return this.featureController.getFeature(user, "role", "logout")
            .then(
            (ft: platform.feature) => {
                let rs = new platform.ResponseMessage<platform.userToken>();

                if (ft && ft.effect == "allow") {//允许访问本方法
                    user.userinfo.status = "01";
                    rs.header.rtnCode = "00";
                    rs.header.rtnMsg.message = "成功！"

                } else {
                    rs.header.rtnCode = "01";
                    rs.header.rtnMsg.message = "当前用户无权限！"
                }
                rs.body = user;
                return rs;
            }
            );

    }
}

